# Console menu
from src.core.item_manager import add_item, delete_item, list_items, clear
from src.storage import file_manager
from src.ui.console.display import display_items

import os

DATA_PATH = os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(__file__)))), 'data', 'items.json')

def main_menu():
    pass
    
    while True:
        print("\n====== Bakery Menu ======")
        print("1. Create Item")
        print("2. Display Items")
        print("3. Delete Item")
        print("4. Save Items")
        print("5. Load Items")
        print("6. Exit")
        choice = input("Enter your choice (1-6): ")

        if choice == '1':
            name = input("Enter item name: ")
            try:
                price = float(input("Enter item price: "))
                production_date = input("Enter production date (YYYY-MM-DD): ")
                success, msg = add_item(name, price, production_date)
                print(msg)
            except ValueError:
                print("Invalid price or date format.")
        elif choice == '2':
            display_items(list_items())
        elif choice == '3':
            try:
                id_ = int(input("Enter item id to delete: "))
            except ValueError:
                print("Invalid ID.")
                continue
            success, msg = delete_item(id_)
            print(msg)
        elif choice == '4':
            items_to_save = list_items()
            try:
                import json
                with open(DATA_PATH, 'w') as f:
                    json.dump(items_to_save, f, indent=2)
                print(f"Items saved to {DATA_PATH}")
            except Exception as e:
                print(f"Error saving items: {str(e)}")
        elif choice == '5':
            try:
                import json
                if os.path.exists(DATA_PATH):
                    with open(DATA_PATH, 'r') as f:
                        items_data = json.load(f)
                    clear()
                    for item in items_data:
                        add_item(item['name'], item['price'], item['production_date'])
                    print(f"Items loaded from {DATA_PATH}")
                else:
                    print(f"File not found: {DATA_PATH}")
            except Exception as e:
                print(f"Error loading items: {str(e)}")
        elif choice == '6':
            print("Bye!")
            break
        else:
            print("Invalid option. Please try again.")

if __name__ == "__main__":
    main_menu()
